package com.liaoyin.travel.service.report;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.constant.CommonConstant;
import com.liaoyin.travel.dao.report.UserBriefingMapper;
import com.liaoyin.travel.entity.FileUpload;
import com.liaoyin.travel.entity.UserTeam;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.entity.report.EventReport;
import com.liaoyin.travel.entity.report.UserBriefing;
import com.liaoyin.travel.entity.task.Task;
import com.liaoyin.travel.entity.task.TaskReceivingRecords;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.service.task.TaskReceivingRecordsService;
import com.liaoyin.travel.service.task.TaskService;
import com.liaoyin.travel.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * @项目名：旅投
 * @作者：lijing
 * @描述：员工简报
 * @日期：Created in 2018/7/24 14:55
 */
@Service
public class UserBriefingService extends BaseService<UserBriefingMapper, UserBriefing> {
    
	@Autowired
	private UsersService usersService;
	@Autowired
	private TaskReceivingRecordsService taskReceivingRecordsService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private EventReportService eventReportService;
	/****
	 * 
	     * @方法名：selectMyUserBriefingList
	     * @描述： 查询简报--前后端
	     * @作者： lijing
	     * @日期： 2019年7月24日
	 */
	public List<UserBriefing> selectMyUserBriefingList(Integer num,Integer size,String userId,String qurtyDate,String qurtyType){
		String teamId = "";
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}
		/** 景区id */
		String scenicId = user.getScenicId();
		if(qurtyType == null) {
			//判断是否有权限查询
			if(user.getAssumeOffice()!=null && user.getAssumeOffice().intValue()==1) {
				List<UserTeam> userteamList = user.getUserTeamList();
				if(userteamList==null || userteamList.size() == 0) {
		        	throw new BusinessException("team.is.null");
		        }
				StringBuffer team = new StringBuffer();
		        for(UserTeam u:userteamList) {
		        	team.append("'"+u.getTeamId()+"'"+",");
		        }
				/*boolean b = this.usersService.judgeThisUserInTeam(team.toString(), userId);
				if(!b) {
					throw new BusinessException("auth.is.erreo");
				}*/
				if(team == null){
					throw new BusinessException("team.is.null");
				}
				teamId=team.toString().substring(0, team.toString().lastIndexOf(","));
				team = null;
				System.out.println(teamId);
			}else {
				userId = user.getId();
				user = null;
			}
		}
		PageHelper.startPage(num, size);
		List<UserBriefing> list = this.mapper.selectMyUserBriefingList(userId, qurtyDate,teamId,scenicId);
		if(list !=null && list.size() >0) {
			list.stream().forEach((b) ->{
				if(b.getBriefingPicId() !=null) {
					List<FileUpload> picFileUploadList = FileUploadUtil.getFileUploadList(b.getBriefingPicId());
					if(picFileUploadList !=null && picFileUploadList.size() >0) {
						b.setPicFileUploadList(picFileUploadList);
						List<String> picList = new ArrayList<String>();
						picFileUploadList.stream().forEach((f) ->{
							picList.add(CommonConstant.FILE_SERVER+f.getFilePath());
						});
						b.setPicList(picList);
						picFileUploadList=null;
					}
				}
				if(b.getBriefingAudioId() !=null) {
					List<FileUpload> audioFileUploadList = FileUploadUtil.getFileUploadList(b.getBriefingAudioId());
					b.setAudioFileUploadList(audioFileUploadList);
					if(audioFileUploadList !=null && audioFileUploadList.size() >0) {
						List<String> audioList = new ArrayList<String>();
						audioFileUploadList.stream().forEach((f) ->{
							audioList.add(CommonConstant.FILE_SERVER+f.getFilePath());
						});
						b.setAudioList(audioList);
						audioFileUploadList=null;
					}
				}
				if(b.getBriefingVideoId() !=null) {
					List<FileUpload> videoFileUploadList = FileUploadUtil.getFileUploadList(b.getBriefingVideoId());
					b.setVideoFileUploadList(videoFileUploadList);
					if(videoFileUploadList !=null && videoFileUploadList.size() >0) {
						List<String> videoList = new ArrayList<String>();
						videoFileUploadList.stream().forEach((f) ->{
							videoList.add(CommonConstant.FILE_SERVER+f.getFilePath());
						});
						b.setVideoList(videoList);
						videoFileUploadList=null;
					}
				}
			});
		}
		System.out.println(list.toString());
		return list;
	}
	
	/****
	 * 
	     * @方法名：insertUserBriefing
	     * @描述： 新增简报--前端
	     * @作者： lijing
	     * @日期： 2019年7月24日
	 */
	@Transactional(rollbackFor = Exception.class)
	public int insertUserBriefing(UserBriefing userBriefing) {
		
		UserInfo user = PartyUtil.getCurrentUserInfo();
		Optional.ofNullable(user).orElseThrow(() -> new BusinessException("not.login"));

		System.err.println("----新增简报参数----");
		System.err.println(JSON.toJSON(userBriefing));
		int result = 0;
		/** 景区id */
		String scenicId = user.getScenicId();
		userBriefing.setScenicId(scenicId);

		userBriefing.setId(UUIDUtil.getUUID());
		userBriefing.setCreatTime(new Date());
		userBriefing.setIsDelete((short)0);
		userBriefing.setUserId(user.getId());

		if(userBriefing.getPicFileUploadList()!=null && userBriefing.getPicFileUploadList().size() >0) {
			userBriefing.setBriefingPicId(FileUploadUtil.saveFileUploadList(userBriefing.getPicFileUploadList(), ""));
		}
		if(userBriefing.getAudioFileUploadList()!=null && userBriefing.getAudioFileUploadList().size() >0) {
			userBriefing.setBriefingAudioId(FileUploadUtil.saveFileUploadList(userBriefing.getAudioFileUploadList(), ""));
		}
		if(userBriefing.getVideoFileUploadList() != null && userBriefing.getVideoFileUploadList().size() >0) {
			userBriefing.setBriefingVideoId(FileUploadUtil.saveFileUploadList(userBriefing.getVideoFileUploadList(), ""));
		}

		result = this.mapper.insertSelective(userBriefing);

		/**
		 * 如果任务对应有事件ID，将事件设置为已处理
		 */
		if(StringUtil.isNotEmpty(userBriefing.getTaskId())){
			Task task = taskService.selectById(userBriefing.getTaskId());
			if(task!=null && StringUtil.isNotEmpty(task.getEventId())){
				EventReport eventReport = eventReportService.selectById(task.getEventId());
				eventReport.setEventProgress(Short.valueOf("2"));
				eventReportService.updateSelectiveById(eventReport);
			}
		}

		if (userBriefing.getTaskId() != null && !"".equals(userBriefing.getTaskId())){
			Task task = this.taskService.selectTaskByIdOnMoble(userBriefing.getTaskId());
			List<TaskReceivingRecords> records = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(userBriefing.getTaskId(), null, null);
			for (TaskReceivingRecords record : records) {
				record.setTastStatus((short)5);
				record.setTaskEndTime(new Date());
				this.taskReceivingRecordsService.updateTaskReceivingRecords(record);
			}
			task.setTaskStatus("5");
			this.taskService.updateById(task);
			String s1 = tempTaskMap.get(task.getId() + "-event");
			if (null != s1){
				this.eventReportService.updateEventProgress(2,s1);
			}
			if (userBriefing.getTaskId().equals(tempTaskMap.get("userBriefing"))){
				Map<String, String> params = new HashMap<>();
				Map<String, String> headers = new HashMap<>();
				headers.put("Authorization","B8C13E9F1F1363499A3B5FA32EA5F39B");
				params.put("UserId", userBriefing.getUserId());
				params.put("BriefingName", userBriefing.getBriefingName());
				params.put("BriefingContext", userBriefing.getBriefingContext());
				String t = DateUtil.formatyyyyMMddHHmmss(userBriefing.getCreatTime());
				params.put("CreatTime", JSON.toJSONString(t));
				params.put("TaskId", userBriefing.getTaskId());
				ArrayList<String> picPathList = new ArrayList<>();
				if (userBriefing.getBriefingPicId() != null && !"".equals(userBriefing.getBriefingPicId())) {
					List<FileUpload> picList = FileUploadUtil.getFileUploadList(userBriefing.getBriefingPicId());

					for (FileUpload picUpload : picList) {
						picPathList.add(picUpload.getFilePath());
					}
					picList=null;
				}
				ArrayList<String> audioPathList = new ArrayList<>();
				if (userBriefing.getBriefingAudioId() != null && !"".equals(userBriefing.getBriefingAudioId())){
					List<FileUpload> audioList = FileUploadUtil.getFileUploadList(userBriefing.getBriefingAudioId());

					for (FileUpload upload : audioList) {
						audioPathList.add(upload.getFilePath());
					}
					audioList=null;
				}
				ArrayList<String> videoPathList = new ArrayList<>();
				if (userBriefing.getBriefingVideoId() != null && !"".equals(userBriefing.getBriefingVideoId())) {
					List<FileUpload> videoList = FileUploadUtil.getFileUploadList(userBriefing.getBriefingVideoId());

					for (FileUpload videoUpload : videoList) {
						videoPathList.add(videoUpload.getFilePath());
					}
					videoList=null;
				}
				params.put("PicList", JSON.toJSONString(picPathList));
				params.put("AudioList", JSON.toJSONString(audioPathList));
				params.put("VideoList", JSON.toJSONString(videoPathList));
				try {
					String s = HttpClientUtils.postForm("http://39.106.3.55:8000/sys/fire/receiveFireTaskReturnMsg", params, headers, null, null);
					System.out.println(s);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (userBriefing.getTaskId().equals(tempTaskMap.get("cleaningTask"))){
				HashMap<String, String> apiCleaing = new HashMap<>();
				Users users = this.usersService.selectUsersById(userBriefing.getUserId());
				apiCleaing.put("operatorName",user.getNickName());
				try {
					HttpClientUtils.postForm("http://lhldgis.1000fun.com/equipment/updateLJTStatus",apiCleaing,null,null,null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	
	/****
	 * 
	     * @方法名：selectUserBriefingById
	     * @描述： 查询简报详情
	     * @作者： lijing
	     * @日期： 2019年7月24日
	 */
	public UserBriefing selectUserBriefingById(String id) {

		Optional.ofNullable(id).orElseThrow(() -> new BusinessException("id.is.null"));

		UserBriefing ub = this.mapper.selectUserBriefingDetailsById(id);
		if (null != ub.getBriefingPicId()) {
			ub.setPicFileUploadList(FileUploadUtil.getFileUploadList(ub.getBriefingPicId()));
		}
		if (null != ub.getBriefingAudioId()) {
			ub.setAudioFileUploadList(FileUploadUtil.getFileUploadList(ub.getBriefingAudioId()));
		}
		if (null != ub.getBriefingVideoId()) {
			ub.setVideoFileUploadList(FileUploadUtil.getFileUploadList(ub.getBriefingVideoId()));
		}
		return ub;
	}
	
	/****
	 * 
	     * @方法名：deleteUserBriefingByIds
	     * @描述： 批量删除
	     * @作者： lijing
	     * @日期： 2019年7月24日
	 */
	public void deleteUserBriefingByIds(String ids) {
		
		if(ids == null) {
			throw new BusinessException("id.is.null");
		}
		String[] id = ids.split(",");
		this.mapper.deleteUserBriefingByIds(id);
	}

	/**
	　* @description: TODO 根据taskid、userID 查询简报详情
	　* @param [taskId, userId]
	　* @return com.liaoyin.travel.entity.report.UserBriefing
	　* @throws
	　* @author privatePanda777@163.com
	　* @date 2019/8/7 20:12
	　*/
	public List<UserBriefing> getUserBriefingByTaskIdAndUserId(String taskId,String userId){
		UserBriefing userBriefing = new UserBriefing();
		userBriefing.setTaskId(taskId);
		if (null != userId && !"".equals(userId)) {
			userBriefing.setUserId(userId);
		}
		List<UserBriefing> one = this.mapper.select(userBriefing);
		return one;
	}


}
